package com.example.downloadmanagerdemo.download;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class DownloadRecordHelper {
	private static final String DOWNLOAD_SPF_TAG = "download_manager_spf";
	private static final String DOWNLOAD_SPF_KEY_SIZE = "size";
	private static final String DOWNLOAD_SPF_KEY_DOWNLOADED_SIZE = "downloaded_size";
	private static final String DOWNLOAD_SPF_KEY_FINISH = "finish";

	private Application app;

	private static DownloadRecordHelper sInstance = null;

	private DownloadRecordHelper() {

	}

	public static DownloadRecordHelper getInstance() {
		if (sInstance == null) {
			sInstance = new DownloadRecordHelper();
		}
		return sInstance;
	}

	public void init(Application app) {
		this.app = app;
	}

	private SharedPreferences getSPF() {
		return app.getSharedPreferences(DOWNLOAD_SPF_TAG, Context.MODE_PRIVATE);
	}

	public long readSavedSize(String packageName) {
		SharedPreferences spf = getSPF();
		return spf.getLong(DOWNLOAD_SPF_KEY_DOWNLOADED_SIZE + packageName, 0);
	}

	public long readSize(String packageName) {
		SharedPreferences spf = getSPF();
		return spf.getLong(DOWNLOAD_SPF_KEY_SIZE + packageName, 0);
	}

	public void writeSavedSize(long saveSize, String packageName) {
		Editor editor = getSPF().edit();
		editor.putLong(DOWNLOAD_SPF_KEY_DOWNLOADED_SIZE + packageName, saveSize).commit();
	}

	public void writeSize(long size, String packageName) {
		Editor editor = getSPF().edit();
		editor.putLong(DOWNLOAD_SPF_KEY_SIZE + packageName, size).commit();
	}

	public void clearRecord(String packageName) {
		Editor editor = getSPF().edit();
		editor.remove(DOWNLOAD_SPF_KEY_SIZE + packageName);
		editor.remove(DOWNLOAD_SPF_KEY_DOWNLOADED_SIZE + packageName);
		editor.commit();
	}

	public void signFinish(String packageName) {
		Editor editor = getSPF().edit();
		editor.putBoolean(DOWNLOAD_SPF_KEY_FINISH + packageName, true).commit();
	}

	public boolean isFinished(String packageName) {
		return getSPF().getBoolean(DOWNLOAD_SPF_KEY_FINISH, false);
	}
}
